package vip.xiaonuo.smzq.core.tools.databas;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.SQLException;

@Configuration // 将此类声明为 Spring 配置类
public class DatabaseConnectionPool {

    @Value("${spring.datasource.dynamic.datasource.master.url}")
    private String DB_URL;

    @Value("${spring.datasource.dynamic.datasource.master.username}")
    private String USER;

    @Value("${spring.datasource.dynamic.datasource.master.password}")
    private String PASS;

    private static HikariDataSource dataSource;

    @PostConstruct
    public void init() {
        try {
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(DB_URL);
            config.setUsername(USER);
            config.setPassword(PASS);
            config.setMaximumPoolSize(20); // 设置最大连接数
            config.setMinimumIdle(5); // 设置最小空闲连接数
            config.setConnectionTimeout(30000); // 设置连接超时时间（毫秒）
            config.setIdleTimeout(600000); // 设置空闲连接超时时间（毫秒）
            config.setMaxLifetime(1800000); // 设置连接的最大生命周期（毫秒）

            dataSource = new HikariDataSource(config);
        } catch (Exception e) {
            throw new RuntimeException("Error initializing database connection pool", e);
        }
    }

    public static Connection getConnection() throws SQLException {
        if (dataSource == null) {
            throw new IllegalStateException("DataSource is not initialized");
        }
        return dataSource.getConnection();
    }

    public static void closeDataSource() {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.close();
        }
    }
}
